package com.wechat.Util;

import java.util.ArrayList;
import java.util.List;

import com.wechat.po.AccessToken;
import com.wechat.po.WeixinUser;
import com.wechat.po.WeixinUserList;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class AdvanceUtil {
	
	
	public static String makeTextCustomMessage(String openId,String content){
		content = content.replace("\"", "\\\"");
		String jsonMsg = "{\"touser\":\"%s\",\"msgtype\":\"text\",\"text\":{\"content\":\"%s\"}}";
		return String.format(jsonMsg, openId,content);
	}
	/**
	 * 发送客服消息
	 * @param accessToken
	 * @param jsonMsg
	 * @return
	 */
	public static boolean sendCustomMessage(String accessToken,String jsonMsg){
		boolean result = false;
		//拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		String respJson = CommonUtil.httpsRequest(requestUrl, "POST", jsonMsg);
		JSONObject jsonObject = JSONObject.fromObject(respJson);
		if(null!=jsonObject){
			int errorCode = jsonObject.getInt("errcode");
			String errorMsg = jsonObject.getString("errmsg");
			if(0 == errorCode){
				result=true;
			} else{
				System.out.println("客服消息发送失败"+errorCode);
			}
		}
		return result;
	}
	
	/**
	 * 根据标签群发文本消息
	 * @param accessToken
	 * @param tagId
	 * @param content
	 * @return
	 */
	public static boolean sendMassMessageByTag(String accessToken,int tagId,String content){
		boolean result = false;
		//拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		String jsonMsg = "{\"filter\":{\"is_to_all\":false,\"tag_id\":%d},\"text\":{\"content\":\"%s\"},\"msgtype\":\"text\"}";
		jsonMsg = String.format(jsonMsg,tagId,content);
		String respJson = CommonUtil.httpsRequest(requestUrl, "POST", jsonMsg);
		JSONObject jsonObject = JSONObject.fromObject(respJson);
		if(null!=jsonObject){
			int errorCode = jsonObject.getInt("errcode");
			String errorMsg = jsonObject.getString("errmsg");
			if(0 == errorCode){
				result=true;
			} else{
				System.out.println("群发消息发送失败"+errorCode);
			}
		}
		return result;
	}
	
	/**
	 * 根据openid列表群发文本消息
	 * @param accessToken
	 * @param tagId
	 * @param content
	 * @return
	 */
	public static boolean sendMassMessageByOpenIdList(String accessToken,List<String> openIdList,String content){
		boolean result = false;
		//拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		String jsonMsg = "{\"touser\":%s,\"msgtype\": \"text\",\"text\": { \"content\": \"%s\"}}";
		jsonMsg = String.format(jsonMsg,JSONArray.fromObject(openIdList).toString(),content);
		String respJson = CommonUtil.httpsRequest(requestUrl, "POST", jsonMsg);
		JSONObject jsonObject = JSONObject.fromObject(respJson);
		if(null!=jsonObject){
			int errorCode = jsonObject.getInt("errcode");
			String errorMsg = jsonObject.getString("errmsg");
			if(0 == errorCode){
				result=true;
			} else{
				System.out.println("id群发消息发送失败"+errorCode);
			}
		}
		return result;
	}
	
	/**
	 * 获取用户基本信息
	 * @param accessToken
	 * @param openId
	 * @return
	 */
	public static WeixinUser getUserInfo(String accessToken,String openId){
		WeixinUser weixinUser = null;
		//拼接请求地址
		String requestUrl = " https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN ";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
		String respJson = CommonUtil.httpsRequest(requestUrl, "GET", null);
		System.out.println(respJson);
		JSONObject jsonObject = JSONObject.fromObject(respJson);
		if(null!=jsonObject){
			try{
			weixinUser = new WeixinUser();
			weixinUser.setSubscribe(jsonObject.getInt("subscribe"));
			weixinUser.setOpenid(jsonObject.getString("openid"));
			weixinUser.setNickname(jsonObject.getString("nickname"));
			weixinUser.setSex(jsonObject.getInt("sex"));
			weixinUser.setLanguage(jsonObject.getString("language"));
			weixinUser.setCity(jsonObject.getString("city"));
			weixinUser.setProvince(jsonObject.getString("province"));
			weixinUser.setCountry(jsonObject.getString("country"));
			weixinUser.setHeadimgurl(jsonObject.getString("headimgurl"));
			weixinUser.setSubscribeTime(jsonObject.getInt("subscribe_time"));
			//weixinUser.setUnionId(jsonObject.getString("unionid"));
			weixinUser.setRemark(jsonObject.getString("remark"));
			weixinUser.setGroupid(jsonObject.getInt("groupid"));
			}catch (Exception e) {
				if(0==weixinUser.getSubscribe()){
					System.out.println("用户"+weixinUser.getOpenid()+"已经取消关注公众号");
				}else{
					int errorCode = jsonObject.getInt("errcode");
					String errorMsg = jsonObject.getString("errmsg");
					System.out.println("用户信息获取失败"+errorCode);
				}
			}
			
		}
		return weixinUser;
	}
	
	/**
	 * 获取用户列表
	 * @param accessToken
	 * @param nextOpenId
	 * @return
	 */
	public static WeixinUserList getUserList(String accessToken,String nextOpenId){
		WeixinUserList weixinUserList = null;
		//拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("NEXT_OPENID", nextOpenId);
		String respJson = CommonUtil.httpsRequest(requestUrl, "GET", null);
		JSONObject jsonObject = JSONObject.fromObject(respJson);
		if(null!=jsonObject){
			try{
			weixinUserList = new WeixinUserList();
			weixinUserList.setTotal(jsonObject.getInt("total"));
			weixinUserList.setCount(jsonObject.getInt("count"));
			weixinUserList.setNextOpenId(jsonObject.getString("next_openid"));
			
			JSONObject dataObject = (JSONObject)jsonObject.get("data");
			weixinUserList.setOpenIdList(JSONArray.toList(dataObject.getJSONArray("openid"),String.class));
			}catch (Exception e) {
					weixinUserList = null;
					int errorCode = jsonObject.getInt("errcode");
					String errorMsg = jsonObject.getString("errmsg");
					System.out.println("用户信息获取失败"+errorCode);
				}
			}
		return weixinUserList;
		}
	
	public static void main(String[] args) {
		String token = CommonUtil.getAccessToken().getToken().toString();
//		String json = makeTextCustomMessage("ozFZY0oXG5U_aAwDeNVoNdKYBBCs", "我是你爸爸");
//		sendCustomMessage(token, json);
//		sendMassMessageByTag(token, 0, "我是你爸爸");
//		List<String> openIdList = new ArrayList<String>();
//		openIdList.add("ozFZY0oXG5U_aAwDeNVoNdKYBBCs");
//		openIdList.add("ozFZY0qX4cwu7X63oEfzBRpgpjgA");
//		sendMassMessageByOpenIdList(token, openIdList, "我是你爸爸");
		//获取用户基本信息
//		WeixinUser weixinUser = getUserInfo(token, "ozFZY0oXG5U_aAwDeNVoNdKYBBCs");
//		System.out.println(weixinUser.getCity()+""+weixinUser.getNickname());
//		System.out.println(weixinUser.getHeadimgurl());
		//获取用户信息列表
//		WeixinUserList weixinUserList = getUserList(token, "");
//		System.out.println(weixinUserList.getTotal()+" "+weixinUserList.getCount()+"  "+weixinUserList.getNextOpenId());
	}
}
